package luz.javaproxy.gui;

import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.text.DefaultFormatter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class RegexPatternFormatter extends DefaultFormatter {
	private static final long serialVersionUID = -6087687273958561345L;
	protected Matcher matcher;
	private static final Log log = LogFactory.getLog(RegexPatternFormatter.class);
	
	public RegexPatternFormatter(Pattern regex, Class<?> valueClass) {
		setOverwriteMode(false);
		setValueClass(valueClass);
		matcher = regex.matcher("");
	}

	public Object stringToValue(String string) throws ParseException {
		if (string == null){
			log.error("String is null");
			return null;
		}
			
		string=string.trim();
		matcher.reset(string);

		if (!matcher.matches()){
			throw new ParseException("does not match regex", 0);
		}else{
			return super.stringToValue(string); // will honor the 'valueClass' property
		}
	}

}